package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.UserBlock;
import com.yami.shop.bean.vo.UserVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.UserBlockMapper;
import com.yami.shop.service.FriendService;
import com.yami.shop.service.UserBlockService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@AllArgsConstructor
public class UserBlockServiceImpl extends ServiceImpl<UserBlockMapper, UserBlock> implements UserBlockService {
    
    
    private final UserBlockMapper userBlockMapper;
    
    @Autowired
    private FriendService friendService;
    
    @Override
    public IPage<UserVO> page(PageParam<UserVO> page, String userId) {
        IPage<UserVO> iPage = userBlockMapper.page(page, userId);
        return iPage;
    }

    /**
     * 拉黑关系
     * @param userId 当前人
     * @param blockUserId 对方
     * @return isBlock 拉黑对方  isBeiBlock 被对方拉黑
     */
    @Override
    public Map<String, Boolean> isBlock(String userId, String blockUserId) {
        Map<String, Boolean> map = new HashMap<>();
        map.put("isBlock", false);
        map.put("isBeiBlock", false);
        if (!userId.equals(blockUserId)) {
            UserBlock one = getOne(Wrappers.lambdaQuery(UserBlock.class).eq(UserBlock::getUserId, userId).eq(UserBlock::getBlockUserId, blockUserId));
            if (Objects.nonNull(one)) {
                map.put("isBlock", true);
            }
            UserBlock beiOne = getOne(Wrappers.lambdaQuery(UserBlock.class).eq(UserBlock::getUserId, blockUserId).eq(UserBlock::getBlockUserId, userId));
            if (Objects.nonNull(beiOne)) {
                map.put("isBeiBlock", true);
            }
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrDel(String userId, UserBlock userBlock) {
        if (userId.equals(userBlock.getBlockUserId())) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "不可以拉黑自己");
        }
        UserBlock one = getOne(Wrappers.lambdaQuery(UserBlock.class).eq(UserBlock::getUserId, userId).eq(UserBlock::getBlockUserId, userBlock.getBlockUserId()));
        if (Objects.isNull(one)) {
            userBlock.setUserId(userId);
            save(userBlock);
            // 删除粉丝关系
            friendService.removeEachOtherFan(userId, userBlock.getBlockUserId());
        } else {
            removeById(one.getId());
        }
    }

}
